// index.ts
import { defineComponent, h, type PropType, toRefs } from 'vue';
import { Descriptions as AntdDescriptions, DescriptionsItem } from 'ant-design-vue';

// 定义 schema 类型
export interface SchemaItem {
  field: string;
  label: string;
  span?: number;
  className?: string;
  labelClassName?: string;
  contentClassName?: string;
  render?: (value: any, data: Record<string, any>) => any;
}

// 封装的 Description 组件
export const Description = defineComponent({
  name: 'MyDescription',
  props: {
    schema: {
      type: Array as PropType<SchemaItem[]>,
      required: true,
    },
    data: {
      type: Object as PropType<Record<string, any>>,
      default: () => ({}),
    },
    // 透传所有 Descriptions 组件的属性
    ...AntdDescriptions.props,
  },
  setup(props, { slots }) {
    const { schema, data } = toRefs(props);

    return () =>
      h(
        AntdDescriptions,
        { ...props },
        {
          default: () =>
            schema.value.map((item: SchemaItem, index: number) => {
              const value = data.value[item.field];

              // 确保渲染内容正确传递
              const content = item.render ? item.render(value, data.value) : value !== undefined ? value : '-';

              return h(
                DescriptionsItem,
                {
                  key: item.field || index,
                  label: item.label,
                  span: item.span,
                  className: item.className,
                  labelClassName: item.labelClassName,
                  contentClassName: item.contentClassName,
                },
                // 关键修改：使用对象形式的children
                {
                  default: () => [content],
                  ...slots,
                }
              );
            }),
        }
      );
  },
});

// 组合式函数保持不变
export function useDescription(options: any) {
  const Component = defineComponent({
    inheritAttrs: false,
    setup() {
      return () => h(Description, options);
    },
  });

  return [Component];
}
